package scheduler

import (
	"learngo/crawler/engine"
)

// 增加一个工作队列来方便控制
type QueuedScheduler struct {
	// 定义结构
	requestChan chan engine.Request
	workerChan  chan chan engine.Request // woker对外的接口是chan engine.Request

}

func (s *QueuedScheduler) Submit(r engine.Request) {
	s.requestChan <- r
}

func (s *QueuedScheduler) WorkerReady(w chan engine.Request) {
	s.workerChan <- w
}

func (s *QueuedScheduler) WorkerChan() chan engine.Request {
	// 每个worker都有自己的channel
	return make(chan engine.Request)
}

func (s *QueuedScheduler) Run() {
	s.workerChan = make(chan chan engine.Request)
	s.requestChan = make(chan engine.Request)
	go func() {
		var requestQ []engine.Request
		var workerQ []chan engine.Request
		for {
			var activeRequest engine.Request
			var activeWorker chan engine.Request
			if len(requestQ) > 0 &&
				len(workerQ) > 0 {
				activeWorker = workerQ[0]
				activeRequest = requestQ[0]
			}
			select {
			// 两件事情都是独立的都有可能发生
			case r := <-s.requestChan:
				requestQ = append(requestQ, r) // 收到r发送到队列当中
			case w := <-s.workerChan:
				workerQ = append(workerQ, w)
			case activeWorker <- activeRequest:
				// 同时都有时进行处理，传递数据
				workerQ = workerQ[1:]
				requestQ = requestQ[1:]
			}

		}
	}()
}
